package com.wzq.demo.interceptor;

import com.wzq.mvcframework.annotations.WzqSecurity;
import com.wzq.mvcframework.annotations.WzqService;
import com.wzq.mvcframework.interceptor.AdvancedInterceptor;
import com.wzq.mvcframework.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import java.security.Security;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author wzq.Jolin
 * @company none
 * @create 2020-07-14 14:13
 */
@WzqService
public class SecurityInterceptor   implements AdvancedInterceptor {
    @Override
    public boolean preHandler(HttpServletRequest request, Handler handler) {
        Set<String> roles = new HashSet<>();
        if (handler.getController().getClass().isAnnotationPresent( WzqSecurity.class)) {
            WzqSecurity security = handler.getController().getClass().getAnnotation(WzqSecurity.class);
            if (security.roles().length > 0) {
                roles.addAll( Arrays.asList(security.roles()));
            }
        }

        if (handler.getMethod().isAnnotationPresent(WzqSecurity.class)) {
            WzqSecurity security = handler.getMethod().getAnnotation(WzqSecurity.class);
            if (security.roles().length > 0) {
                roles.addAll(Arrays.asList(security.roles()));
            }
        }
        if (roles.isEmpty()) {
            return true;
        }
        String username = request.getParameter("username");
        return roles.contains(username);
    }
}
